package com.example.studentmanagement2.repository.JdbcRepository;

import com.example.studentmanagement2.model.User;
import com.example.studentmanagement2.repository.Repository.UserRepository;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;

@Repository
public class JdbcUserRepository implements UserRepository {

    private final JdbcTemplate jdbcTemplate;

    public JdbcUserRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public List<User> findAll() {
        return jdbcTemplate.query(
                "SELECT * FROM user", // 假设表名已从students改为users
                (rs, rowNum) -> new User(
                        rs.getString("id"),
                        rs.getString("username"),
                        rs.getString("password"),
                        rs.getString("real_name"),
                        rs.getString("role")
                )
        );
    }

    @Override
    public Optional<User> findById(String id) {
        try {
            return jdbcTemplate.queryForObject(
                    "SELECT * FROM user WHERE id = ?", // 假设表名已从students改为users
                    new Object[]{id},
                    (rs, rowNum) -> Optional.of(new User(
                            rs.getString("id"),
                            rs.getString("username"),
                            rs.getString("password"),
                            rs.getString("real_name"),
                            rs.getString("role")
                    ))
            );
        } catch (EmptyResultDataAccessException e) {
            return Optional.empty(); // 显式处理空结果
        }
    }

    @Override
    public User save(User user) {
        jdbcTemplate.update(
                "INSERT INTO user (id, username,password,real_name,role) VALUES (?, ?, ?, ?, ?)", // 假设表名已从students改为users
                user.getId(), user.getUsername(), user.getPassword(),user.getReal_name(),user.getRole()
        );
        return user;
    }

    @Override
    public void update(User user, String originalId) {
        jdbcTemplate.update(
                "UPDATE user SET id=?, username=?,password=?,real_name=?,role=? WHERE id=?", // 假设表名已从students改为users
                user.getId(),     // 新学号
                user.getUsername(),
                user.getPassword(),
                user.getReal_name(),
                user.getRole(),
                originalId          // 原始学号（WHERE 条件）
        );
    }

    @Override
    public void deleteById(String id) {
        jdbcTemplate.update("DELETE FROM user WHERE id = ?", id); // 假设表名已从students改为users
    }

    @Override
    public boolean existsById(String id) {
        String sql = "SELECT COUNT(*) FROM user WHERE id = ?"; // 假设表名已从students改为users
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class, id);
        return count != null && count > 0;
    }

    @Override
    public List<User> search(String keyword) {
        String sql = "SELECT * FROM user WHERE " + // 假设表名已从students改为users
                "id LIKE ? OR role LIKE ? OR real_name LIKE ?";
        String pattern = "%" + keyword + "%";
        return jdbcTemplate.query(
                sql,
                new Object[]{pattern, pattern, pattern},
                (rs, rowNum) -> new User(
                        rs.getString("id"),
                        rs.getString("username"),
                        rs.getString("password"),
                        rs.getString("real_name"),
                        rs.getString("role")
                )
        );
    }


}
